package com.example.xy.searchphone.mvp.impl;

import android.util.Log;

import com.example.xy.searchphone.business.HttpUtil;
import com.example.xy.searchphone.model.Phone;
import com.example.xy.searchphone.mvp.MvpMainView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xy on 2017/12/17.
 */

public class MainPresenter extends BasePresenter{
    private static final String  mUrl= "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";

    MvpMainView mvpMainView;
    Phone mPhone;

    public Phone getPhoneInfo(){
        return mPhone;
    }
    public MainPresenter(MvpMainView mainView){
        mvpMainView=mainView;
    }

    public void searchPhoneInfo(String phone){
        if (phone.length()!=11){
            mvpMainView.showToast("请输入正确的手机号");
            return;
        }else{
            sendHttp(phone);
        }
    }

    private void sendHttp(String phone){
        Map<String,String>map = new HashMap<>();
        map.put("tel",phone);
        HttpUtil httpUtil = new HttpUtil(new HttpUtil.HttpResponse() {
            @Override
            public void onSuccess(Object object) {
                String jsonStr = object.toString();
                Log.v("MainPresent",jsonStr);
                int index= jsonStr.indexOf("{");
                jsonStr=jsonStr.substring(index,jsonStr.length());
                mPhone=parseModelWithOrgJson(jsonStr);
                mvpMainView.updateView();
            }

            @Override
            public void onFail(String error) {
                mvpMainView.showToast(error);
            }
        });
        httpUtil.sendGetHttp(mUrl,map);
    }

    private Phone parseModelWithOrgJson(String json){
        Phone phone = new Phone();
        try {
            JSONObject jsonObject = new JSONObject(json);
            phone.setTelString(jsonObject.get("telString").toString());
            phone.setProvince(jsonObject.get("province").toString());
            phone.setCatName(jsonObject.get("catName").toString());
            phone.setCarrier(jsonObject.get("carrier").toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return phone;
    }
}
